﻿using System.Collections.Generic;
using Protocol.Dto.Fight;
using UnityEngine;

namespace Script.Character
{
    public class DeskCtrl : CharacterBase
    {
        private void Awake()
        {
            Bind(CharacterEvent.UPDATE_SHOW_DESK);
        }


        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case CharacterEvent.UPDATE_SHOW_DESK:
                    updateShowDesk(message as List<CardDto>);
                    break;
            }
        }

        // 自身的卡牌列表
        [SerializeField] private List<CardCtrl> cardCtrlList;

        // 卡牌的父物体
        private Transform cardParent;
        private GameObject cardPrefab;


        // Start is called before the first frame update
        private void Start()
        {
            cardParent = transform.Find("CardPoint");
            cardCtrlList = new List<CardCtrl>();

            cardPrefab = Resources.Load<GameObject>("Card/MyCard");
        }

        private void updateShowDesk(List<CardDto> _cardLists)
        {
            if (cardCtrlList.Count > _cardLists.Count)
            {
                // 原来桌面比现在牌多
                // 复用之前创建的卡牌
                int index = 0;

                foreach (CardCtrl cardCtrl in cardCtrlList)
                {
                    cardCtrl.gameObject.SetActive(true);
                    cardCtrl.Init(_cardLists[index], index, true);
                    index++;

                    // 如果牌没了
                    if (index == _cardLists.Count)
                    {
                        break;
                    }
                }

                for (int i = index; i < _cardLists.Count; i++)
                {
                    cardCtrlList[i].gameObject.SetActive(false);
                }
            }
            else
            {
                // 原来桌面比现在牌少
                // 复用之前创建的卡牌
                int index = 0;

                foreach (CardCtrl cardCtrl in cardCtrlList)
                {
                    cardCtrl.gameObject.SetActive(true);
                    cardCtrl.Init(_cardLists[index], index, true);
                    index++;
                }

                for (int i = index; i < _cardLists.Count; i++)
                {
                    CreateGo(_cardLists[i], i, cardPrefab);
                }
            }
        }

        /// <summary>
        /// 创建卡牌游戏物体
        /// </summary>
        /// <param name="cardDto">卡牌数据</param>
        /// <param name="index">确定位置的下标</param>
        /// <param name="prefab">卡牌原型</param>
        private void CreateGo(CardDto cardDto, int index, GameObject prefab)
        {
            GameObject card = Instantiate(prefab, cardParent);

            card.name = cardDto.Name;

            CardCtrl cardCtrl = card.GetComponent<CardCtrl>();

            cardCtrl.Init(cardDto, index, true);


            // 存储本地
            cardCtrlList.Add(cardCtrl);
        }
    }
}